package user

import (
	"github.com/go-playground/validator/v10"
	"github.com/labstack/echo/v4"
	"techoiceness.com/aiagent/llm-gateway/internal/agent"
	"techoiceness.com/aiagent/llm-gateway/internal/auth"
	"techoiceness.com/aiagent/llm-gateway/internal/config"
	"techoiceness.com/aiagent/llm-gateway/internal/llm"
	"techoiceness.com/aiagent/llm-gateway/internal/repository"
	"techoiceness.com/aiagent/llm-gateway/internal/service"
)

// UserHandler 用户处理器 - 统一的用户相关功能处理器
type UserHandler struct {
	cfg            *config.Config
	jwtManager     *auth.JWTManager
	agentHub       *agent.AgentHub
	titleGenerator *service.TitleGenerator
	repos          repository.ContainerInterface
	validator      *validator.Validate
}

// NewUserHandler 创建用户处理器
func NewUserHandler(
	cfg *config.Config,
	jwtManager *auth.JWTManager,
	llmProviderManager *llm.ProviderManager,
	agentHub *agent.AgentHub,
	repos repository.ContainerInterface,
) *UserHandler {
	titleGenerator := service.NewTitleGenerator(llmProviderManager)

	return &UserHandler{
		cfg:            cfg,
		jwtManager:     jwtManager,
		agentHub:       agentHub,
		titleGenerator: titleGenerator,
		repos:          repos,
		validator:      validator.New(),
	}
}

// RegisterRoutes 注册用户相关路由
func (h *UserHandler) RegisterRoutes(api *echo.Group, authMiddleware *auth.AuthMiddleware, authEntityFactory func() auth.Authenticatable) {
	// 认证相关路由（无需认证）
	user := api.Group("/user")

	auth := user.Group("/auth")
	{
		auth.POST("/login", h.Login)
	}

	// 需要认证的聊天路由
	chat := user.Group("/chat", authMiddleware.JWT(authEntityFactory))
	{
		// 主聊天接口
		chat.POST("", h.Chat)

		// 会话管理
		chat.POST("/conversations", h.CreateConversation)
		chat.GET("/conversations", h.GetConversations)
		chat.DELETE("/conversations/:id", h.DeleteConversation)
		chat.GET("/conversations/:conversation_id/messages", h.GetConversationMessages)

		// 对话历史（代理到AI系统）
		chat.GET("/conversations/:conversation_id/history", h.GetConversationHistory)
		chat.GET("/conversations/:conversation_id/latest", h.GetLatestResponse)
	}
}
